/*
 * @lc app=leetcode.cn id=124 lang=csharp
 *
 * [124] 二叉树中的最大路径和
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left;
 *     public TreeNode right;
 *     public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
public class Solution {

  private int _max_sum = -1001;
  private int _min_value = -1001;

  public int MaxPathSum(TreeNode root)
  {
    Dfs(root);
    return _max_sum;
  }

  public int Dfs(TreeNode root)
  {
    if (root == null) {
      return _min_value;
    }

    int left_value = Dfs(root.left) + root.val;
    int right_value = Dfs(root.right) + root.val;
    int sum = left_value + right_value - root.val;
    _max_sum = Math.Max(root.val, Math.Max(left_value, Math.Max(right_value, Math.Max(sum, _max_sum))));

    if (root.val > left_value && root.val > right_value) {
      return root.val;
    }

    return Math.Max(left_value, right_value);
  }
}
// @lc code=end

